package packets.c2spackets;

import network.MCConnection;
import entities.Player;
import exceptions.UnrecoverableException;
import packets.PacketHandler;
import packets.SPacket;
import packets.s2cpackets.S0x01;
import packets.s2cpackets.S0x06;
import packets.s2cpackets.S0x0D;
import world.WorldState;

public class P0x01 extends PacketHandler{

	public P0x01(WorldState state) {
		super(state);
	}



	@Override
	public void handle(MCConnection conn) throws UnrecoverableException {		

		@SuppressWarnings("unused")
		int protocol = conn.r.readInt();
		String username = conn.r.readString();
		conn.r.readBytes(18); //18 unused bytes
		
		//TODO: Validate if this user login is correct :)
		//Create a new player object, and set it to the connection.
		// also inform the world state of the new player
		Player player = worldstate.entitymanager().getNewPlayer(username);
		conn.setPlayer(player);
		getWorldState().connectionManager().addPlayer(conn);

		
		/**
		 * Reply some server information :)
		 */
		SPacket s = new S0x01(player);
		conn.send(s);
				
		//returning:
		//  ENTITY ID		(Int)
		//  EMPTY STRING	(BB)
		//  MAP SEED 		(LONG)
		//  LEVEL TYPE		(String) [Default || SUPERFLAT]
		//  SERVER MODE		(Int)    [0 survival | 1 creative]
		//  DIMENSION		(B)	     [-1 Nether | 0 OverWorld | 1 The End]
		//  Difficulty		(B)
		//  World Height	(b)	     [128]
		//  MAX PLAYERS		(b)
		
		
		this.getWorldState().mapmanager().sendInitialMap(player);
		
		//Send the players spawnpoint...
		conn.send(new S0x06(player));
		
		//Send the players initial look and position. After this, the
		// 'log-in' is 'finished'.
		s = new S0x0D(player);
		conn.send(s);
		
		getWorldState().playermanager().registerPlayer(player);
		
	}


	
	
}
